/*
 * Funambol is a mobile platform developed by Funambol, Inc.
 * Copyright (C) 2008 Funambol, Inc.
 *
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the GNU Affero General Public License version 3 as published by
 * the Free Software Foundation with the addition of the following permission
 * added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED
 * WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE
 * WARRANTY OF NON INFRINGEMENT  OF THIRD PARTY RIGHTS.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
 * details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program; if not, see http://www.gnu.org/licenses or write to
 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 * MA 02110-1301 USA.
 *
 * You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite
 * 305, Redwood City, CA 94063, USA, or at email address info@funambol.com.
 *
 * The interactive user interfaces in modified source and object code versions
 * of this program must display Appropriate Legal Notices, as required under
 * Section 5 of the GNU Affero General Public License version 3.
 *
 * In accordance with Section 7(b) of the GNU Affero General Public License
 * version 3, these Appropriate Legal Notices must retain the display of the
 * "Powered by Funambol" logo. If the display of the logo is not reasonably
 * feasible for technical reasons, the Appropriate Legal Notices must display
 * the words "Powered by Funambol".
 */


#import <UIKit/UIKit.h>


#import "common.h"
#import "LogSettingsView.h"
#import "base/Log.h"
#import "UIController.h"
#import "LogLevelView.h"
#import "LogView.h"
#import "customs.h"
#import "base/util/StringBuffer.h"
#import "stringUtils.h"
#import "FunambolAPI.h"

USE_NAMESPACE


@implementation LogSettingsView

- (BOOL) isSendLogEnabled{
    return (CUSTOM_SEND_LOG != 0);
}

- (id)init {	self = [super init];
	if (self)
	{
		// this title will appear in the navigation bar
		self.title = NSLocalizedString(@"Log",@"Log");
		
		menuList = [[NSMutableArray alloc] init];
	}
    funBlue = [[UIColor alloc] initWithRed:0.0 green:0.4 blue:0.9 alpha:1.0];
	return self;
}

- (void) loadView{
    UIView *contentView = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]];
	self.view = contentView;
	[contentView release];
    small_font = [UIFont systemFontOfSize:15];
    logLevelLabel = [[UILabel alloc] initWithFrame:CGRectMake(140.0, 7.0, 140.0, 25.0)];

    int loglevelValue = [[FunambolAPI getInstance] getLogLevel];
    if (loglevelValue == 0 ){
        [logLevelLabel setText:NSLocalizedString(@"Error",@"Error")];
    }else if (loglevelValue == 1 ){
        [logLevelLabel setText:NSLocalizedString(@"Info",@"Info")];
    }else if (loglevelValue == 2 ){
        [logLevelLabel setText:NSLocalizedString(@"Debug",@"Debug")];
    }
    
    [logLevelLabel setTextColor:funBlue];
    [logLevelLabel setFont:small_font];
    [logLevelLabel setTextAlignment:UITextAlignmentRight];
    
	self.view.autoresizesSubviews = YES;
    
    LogLevelView* loglevelview = [[LogLevelView alloc] init];
    [menuList addObject:[NSDictionary dictionaryWithObjectsAndKeys:
                         NSLocalizedString(@"Account", @""), @"title",
                         loglevelview, @"viewController",
                         nil]];
	[loglevelview release];
    
    LogView* logview = [[LogView alloc] init];
    [menuList addObject:[NSDictionary dictionaryWithObjectsAndKeys:
                         NSLocalizedString(@"Account", @""), @"title",
                         logview, @"viewController",
                         nil]];
	[logview release];
    

    logTable = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStyleGrouped]; 
	logTable.delegate = self;
    logTable.dataSource = self;
	logTable.rowHeight = 40;
    [logTable reloadData];
    
    logLevelCell = [[UITableViewCell alloc]init];
    [[logLevelCell textLabel] setText:NSLocalizedString(@"LogLevel",@"Log Level")];
    [logLevelCell addSubview:logLevelLabel];
	
    viewLogCell = [[UITableViewCell alloc]init];
    [[viewLogCell textLabel] setText:NSLocalizedString(@"View Log",@"ViewLog")];
      
    sendLogCell = [[UITableViewCell alloc]init];
    [[sendLogCell textLabel] setText:NSLocalizedString(@"Send Log",@"Send Log")];
	
	clearLogButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
	[clearLogButton setFrame:CGRectMake(10.0, 170.0, 300.0, 40.0)];
	[clearLogButton setTitle: @"Clear log file" forState: UIControlStateNormal];
	[clearLogButton addTarget:self action:@selector(clearLogAction:) forControlEvents:UIControlEventTouchDown];
		    
    [self.view addSubview:logTable];
	[self.view addSubview:clearLogButton];
}

- (void) clearLogAction: (id)sender
{
	//Ask if we want to clear the log-file
	UIAlertView* alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Alert", @"Alert")
									   message:NSLocalizedString(@"Clear log file",@"Clear log file")
									  delegate:self 
							 cancelButtonTitle:NSLocalizedString(@"OK",@"OK") 
							 otherButtonTitles:NSLocalizedString(@"Cancel",@"Cancel"), nil];
	[alert setTag:1];
	[alert show];
	[alert release];

}

- (void)alertView:(UIAlertView *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if([actionSheet tag] == 1 && buttonIndex == 0) { //Yes, want to clear the log file
		NSString *logFile = [getiphoneHomeDir() stringByAppendingPathComponent:@"/synclog.txt"];
		//In case we want to delete and not just clear the log-file
		//[[NSFileManager defaultManager] removeItemAtPath:logFile error:NULL];
		NSString *initLogText = @"";
		NSError **errorString;
		if(![initLogText writeToFile:logFile atomically:NO encoding:NSUTF8StringEncoding error:(NSError **)errorString]) {
			NSLog(@"Can not write to log file");
		}
	}
}

//TABLE VIEW

- (UITableViewCellAccessoryType)tableView:(UITableView *)logTable accessoryTypeForRowWithIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellAccessoryDisclosureIndicator;
}

- (UITableViewCell *)tableView:(UITableView *)logTable cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	
    if([self isSendLogEnabled]){ 
        switch (indexPath.section) {
                //account table section
            case 0:
                switch (indexPath.row) {
                    case 0:
                        return logLevelCell;
                    default:
                        break;
                }
                break;
                //sources table section
            case 1:
                switch (indexPath.row) {
                    case 0:
                        return viewLogCell;
                    case 1:
                        return sendLogCell;
                    default:
                        break;
                }
            default:
                break;
        }
    }else{
        switch (indexPath.section) {
                //account table section
            case 0:
                switch (indexPath.row) {
                    case 0:
                        return logLevelCell;
                    default:
                        break;
                }
                break;
                //sources table section
            case 1:
                switch (indexPath.row) {
                    case 0:
                        return viewLogCell;
                    default:
                        break;
                }
            default:
                break;
        }
    }
    return nil;
}

- (void)viewWillAppear:(BOOL)animated
{
	// this UIViewController is about to re-appear, make sure we remove the current selection in our table view
	NSIndexPath *tableSelection = [logTable indexPathForSelectedRow];
	[logTable deselectRowAtIndexPath:tableSelection animated:NO];
}

- (void)tableView:(UITableView *)logTable didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    UIViewController *targetViewController;
	
	if([self isSendLogEnabled]){
        switch (indexPath.section) {
            case 0:
                switch (indexPath.row) {
                    case 0:
                        targetViewController = [[menuList objectAtIndex: 0] objectForKey:@"viewController"];
                        [[self navigationController] pushViewController:targetViewController animated:YES];
                        break;
                    default:
                        break;
                }
                break;
            case 1:
                switch (indexPath.row) {
                    case 0:
                        targetViewController = [[menuList objectAtIndex: 1] objectForKey:@"viewController"];
                        [[self navigationController] pushViewController:targetViewController animated:YES];
                        break;
                    case 1:
                        [self sendLogAction:self];
                        break;
                    default:
                        break;
                }
                break;
            default:
                break;
        }
    }else{
        switch (indexPath.section) {
            case 0:
                switch (indexPath.row) {
                    case 0:
                        targetViewController = [[menuList objectAtIndex: 0] objectForKey:@"viewController"];
                        [[self navigationController] pushViewController:targetViewController animated:YES];
                        break;
                    default:
                        break;
                }
                break;
            case 1:
                switch (indexPath.row) {
                    case 0:
                        targetViewController = [[menuList objectAtIndex: 1] objectForKey:@"viewController"];
                        [[self navigationController] pushViewController:targetViewController animated:YES];
                        break;
                    default:
                        break;
                }
                break;
            default:
                break;
        }
    }
}
- (NSInteger)tableView:(UITableView *)logTable numberOfRowsInSection:(NSInteger)section {
    if([self isSendLogEnabled]){
        switch (section) {
            case 0:
                return 1;
            case 1:
                return 2;
            default:
                break;
        }
    }else{
        switch (section) {
            case 0:
                return 1;
            case 1:
                return 1;
            default:
                break;
        }
    }
    return 0;//should never happen
}



- (NSInteger)numberOfSectionsInTableView:(UITableView *)logTable {
    return 2;
}

- (void)reload {
}

- (void) dealloc{
    [logTable release];
    
    [logLevelCell release];
    [viewLogCell release];
    [sendLogCell release];
    
    [small_font release];
    [logLevelLabel release];
    [funBlue release];
    
    [menuList release];
    [super dealloc];
    
}

- (void)sendLogAction:(id)sender {
    NSString *documentsDirectory = getiphoneHomeDir();
    
    NSString *s = [NSString stringWithFormat:@"%@/synclog.txt",documentsDirectory];
    
    NSFileHandle *logFile = [NSFileHandle fileHandleForReadingAtPath:s];
    NSString *logString;

    if (logFile != nil) {
        NSData *logData = [logFile readDataToEndOfFile];
        [logFile closeFile];
        logString = [[NSString alloc] initWithData:logData encoding:1];
        Funambol::StringBuffer logs([logString UTF8String]);
        [logString release];
        logs.replaceAll("<", "&lt;",0);
        logs.replaceAll(">", "&gt;",0);
        logString = [[NSString alloc] initWithCString:logs.c_str()];
    } else {
        logString = @"Cannot open log";
    }
    
    NSString * to      = NSLocalizedString(@"Send To",      @"Send To");
    NSString * subj    = NSLocalizedString(@"Send Subject", @"Send Subject");
    
    CFStringRef cto    = CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (const CFStringRef)to,        CFSTR(""), CFSTR(""), kCFStringEncodingUTF8);
    CFStringRef csubj  = CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (const CFStringRef)subj,      CFSTR(""), CFSTR(""), kCFStringEncodingUTF8);
    CFStringRef cbody  = CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (const CFStringRef)logString, CFSTR(""), CFSTR(""), kCFStringEncodingUTF8);
    
    NSString * url     = [NSString stringWithFormat:@"mailto:%@?subject=%@&body=%@", (NSString*)cto, (NSString*)csubj, (NSString*)cbody];
    NSURL * URL        = [NSURL URLWithString:url];
    
    [logString release];
    
    CFRelease(cto);
    CFRelease(csubj);
    CFRelease(cbody);
    
    if (URL)
    {
        [[UIApplication sharedApplication] openURL:URL];
    }
    else
    {
        [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Alert", @"Alert") message:NSLocalizedString(@"Cannot Send Logs", @"Cannot Send Logs")
        delegate:self cancelButtonTitle:NSLocalizedString(@"OK", @"OK") otherButtonTitles: nil];
    }
}

-(void)viewDidAppear:(BOOL)animated{
    int loglevelValue = [[FunambolAPI getInstance] getLogLevel];
    if (loglevelValue == 0 ){
        [logLevelLabel setText:NSLocalizedString(@"Error",@"Error")];
    }else if (loglevelValue == 1 ){
        [logLevelLabel setText:NSLocalizedString(@"Info",@"Info")];
    }else if (loglevelValue == 2 ){
        [logLevelLabel setText:NSLocalizedString(@"Debug",@"Debug")];
    }
}

@end
